package com.hkbigdata.ontimer;

import com.hkbigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author liuanbo
 * @creat 2024-05-15-17:10
 * @see 2194550857@qq.com
 */
public class Flink03_OnTimer {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = env.socketTextStream("hadoop102", 9999).flatMap(new FlatMapFunction<String, WaterSensor>() {
            @Override
            public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                String[] split = value.split(",");
                out.collect(new WaterSensor(split[0],
                        Long.valueOf(split[1]),
                        Double.valueOf(split[2])
                ));
            }
        });

        WatermarkStrategy<WaterSensor> waterSensorWatermarkStrategy = WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000L;
                    }
                });

        waterSensorSingleOutputStreamOperator.assignTimestampsAndWatermarks(waterSensorWatermarkStrategy)
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    Double lastVc = 0.0;
                    Long timerTs = Long.MIN_VALUE;

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        //大于的数据
                        if (value.getVc() > lastVc) {
                            //第一条数据
                            //ws_001,1715217672,21
                            if (timerTs == Long.MIN_VALUE) {
                                System.out.println("ctx.timestamp() = " + ctx.timestamp());
                                timerTs = ctx.timestamp() + 5000L;
                                ctx.timerService().registerEventTimeTimer(timerTs);
                            }
                        } else {//将定时器进行删除
                            ctx.timerService().deleteEventTimeTimer(timerTs);
                        }

                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        System.out.println(ctx.getCurrentKey() + "连续5秒钟持续上升，报警");

                    }
                }).print();


        env.execute();


    }
}
